import * as step from '@flow-step/step-toolkit'
import * as fs from "fs";
import {IParams} from "./params";
import {polyglot} from "./i18n";

export function writeParamsToFile(params: IParams) {
    const tmpParamsDir = `/tmp/${params.buildJobID}`;
    if (!fs.existsSync(tmpParamsDir)) {
        fs.mkdirSync(tmpParamsDir, {recursive: true});
    }
    const tmpParamsFile = `${tmpParamsDir}/params`;
    fs.writeFileSync(tmpParamsFile, params.params as string);
    return tmpParamsFile;
}

// sourceFile 直接 chmod 可能存在多个 Job 并发导致 text file busy 问题，拷贝到工作区以区分不同文件
export function copyToTargetBin(sourceBinFile: string, targetBinFile: string) {
    step.debug(`copy binary ${sourceBinFile} to ${targetBinFile}`)
    // 检查目标文件是否存在
    if (fs.existsSync(targetBinFile)) {
        step.debug(`remove ${targetBinFile}`)
        fs.unlinkSync(targetBinFile);
    }
    fs.copyFileSync(sourceBinFile, targetBinFile)

    try {
        const stats = fs.statSync(targetBinFile)
        if ((stats.mode & 0o777) === 0o755) {
            step.debug(`Permissions for ${targetBinFile} is already 755`)
        } else {
            fs.chmodSync(targetBinFile, 0o755)
            step.debug(`Permissions for ${targetBinFile} set to 755`)
        }
    } catch (err) {
        // @ts-ignore
        throw new Error(`Error setting file permissions: ${err.message}`)
    }
    return targetBinFile;
}

export function processJenkinsBuildNumber(jenkinsBuildNumber: string, params: IParams): number {
    if (jenkinsBuildNumber.includes('error')) {
        // 此时 jenkinsBuildNumber 为报错信息，输出到错误日志
        step.errorV1(jenkinsBuildNumber)
        if (jenkinsBuildNumber.includes('403')) {
            step.warnV1(polyglot.t("reminder_jenkins_supports_passwords_and_tokens"));
        }

        return 1
    } else {
        jenkinsBuildNumber = jenkinsBuildNumber.trim()
        step.infoV1(polyglot.t("currently_build_number", {jenkinsBuildNumber: jenkinsBuildNumber}));
        step.infoV1(polyglot.t("jenkins_task_log_address", {jenkinsMaster: params.jenkinsMaster, jenkinsJob: params.jenkinsJob, jenkinsBuildNumber: jenkinsBuildNumber}));
        step.addOutput("ACTION=CHECK")
        step.addOutput(`JENKINS_BUILD_NUMBER=${jenkinsBuildNumber}`)
        step.interaction.addLink(polyglot.t("task_log"), `${params.jenkinsMaster}/job/${params.jenkinsJob}/${jenkinsBuildNumber}/console`)

        return 0
    }
}

export function processBuildResult(buildResult: string, params: IParams): number {
    let execResult = 0
    switch (buildResult.trim()) {
        case "BUILDING":
            step.addOutput(`MESSAGE=${polyglot.t("current_task_is_running")}`)
            step.addOutput("ACTION=CHECK")
            step.addOutput(`JENKINS_BUILD_NUMBER=${params.jenkinsBuildNumber}`)
            break;
        case "ABORTED":
            step.errorV1(polyglot.t("current_task_aborted"))
            step.addOutput("ACTION=ON_FAIL")
            step.addOutput(`RESULT=${buildResult}`)
            execResult = 1
            break;
        case "FAILURE":
            step.errorV1(polyglot.t("current_task_failed"))
            step.addOutput("ACTION=ON_FAIL")
            step.addOutput(`RESULT=${buildResult}`)
            execResult = 1
            break;
        default:
            step.debug(polyglot.t("current_task_success"))
            step.addOutput("ACTION=ON_SUCCESS")
            step.addOutput(`RESULT=${buildResult}`)
    }

    step.interaction.addLink(polyglot.t("task_log"), `${params.jenkinsMaster}/job/${params.jenkinsJob}/${params.jenkinsBuildNumber}/console`)
    return execResult
}